package edu.maine.usm.server;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.joda.time.LocalDate;
import org.motechproject.gateway.OutboundEventGateway;
import org.motechproject.model.MotechEvent;
import org.motechproject.scheduletracking.api.domain.Enrollment;
import org.motechproject.scheduletracking.api.events.constants.EventSubject;
import org.motechproject.scheduletracking.api.repository.AllEnrollments;
import org.motechproject.scheduletracking.api.service.EnrollmentRequest;
import org.motechproject.scheduletracking.api.service.ScheduleTrackingService;
import org.motechproject.server.event.annotations.MotechListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import edu.maine.usm.dto.EnrollmentDTO;
import edu.maine.usm.rpc.EnrollmentService;

@Component
public class EnrollmentServiceImpl implements EnrollmentService {

	private ScheduleTrackingService scheduleTrackingService;
	private OutboundEventGateway eventGateway;
	private AllEnrollments enrollmentRepo;
	private final ArrayList<String> scheduleJobs = new ArrayList<String>();
	private static Logger logger = Logger.getLogger(EnrollmentServiceImpl.class);
	
	@Autowired
	public EnrollmentServiceImpl(
			ScheduleTrackingService scheduleTrackingService,
			OutboundEventGateway eventGateway, AllEnrollments enrollmentsRepo) {
		this.scheduleTrackingService = scheduleTrackingService;
		this.eventGateway = eventGateway;
		this.enrollmentRepo = enrollmentsRepo;

	}
	
	@MotechListener(subjects = { EventSubject.MILESTONE_ALERT })
	public void alertListener(MotechEvent event) {
		scheduleJobs.add(event.toString());
		logger.debug("Event MILESTONE_ALERT: " + event.toString());
	}

	public void enrollInSchedule(String scheduleName, String externalId) {
		EnrollmentRequest request = new EnrollmentRequest(externalId,
				scheduleName, null, new LocalDate());
		scheduleTrackingService.enroll(request);
	}

	public ArrayList<EnrollmentDTO> getPersistedEnrollments() {
		List<Enrollment> enrollments = enrollmentRepo.getAll();
		ArrayList<EnrollmentDTO> dtos = new ArrayList<EnrollmentDTO>();

		for (Enrollment enr : enrollments) {
			EnrollmentDTO dto = new EnrollmentDTO();
			dto.setCurrentMilestoneName(enr.getCurrentMilestoneName());
			dto.setReferenceDate(enr.getReferenceDate().toDate());
			dto.setExternalId(enr.getExternalId());
			dto.setScheduleName(enr.getScheduleName());
			dtos.add(dto);
		}

		return dtos;
	}
}
